/*  G2Remote-js
 *  Gallery2 Remote Protocol JS wrapper library
 *  (c) 2008 Jonathan Lui
 *
 *  G2Remote-js is freely distributable under the terms of an MIT-style license.
 *
 *--------------------------------------------------------------------------*/


var G2Remote = Class.create({
	initialize: function(options) {
		this.gallery_url = options.gallery_url;
		this.username = options.username || null;
		this.password = options.password || null;
		this.needAuth = (this.username && this.password) || false;
	},

	defaultParams: {
		g2_controller: "remote:GalleryRemote"
	},

	/* API Wrappers */
	login: function(options, callback) {
		this._request({
			cmd: "login",
			protocol_version: "2.0",
			uname: options.username,
			password: options.password
		}, callback);
	},

	fetchAlbums: function(options, callback) {
		this._request({
			cmd: "fetch-albums",
			protocol_version: "2.0",
			no_perms: (options.no_perms)?"yes":"no"
		}, callback);
	},

	fetchAlbumsPrune: function(options, callback) {
		this._request({
			cmd: "fetch-albums-prune",
			protocol_version: "2.2",
			no_perms: (options.no_perms)?"yes":"no"
		}, callback);
	},

	albumProperties: function(options, callback) {
		this._request({
			cmd: "album-properties",
			protocol_version: "2.0",
			set_albumName: options.albumName
		}, callback);
	},

	newAlbum: function(options, callback) {
		this._request({
			cmd: "new-album",
			protocol_version: "2.1",
			set_albumName: options.parentAlbumName,
			newAlbumName: options.albumName,
			newAlbumTitle: options.albumTitle,
			newAlbumDesc: options.albumDesc
		}, callback);
	},

	fetchAlbumImages: function(options, callback) {
		this._request({
			cmd: "fetch-album-images",
			protocol_version: "2.4",
			set_albumName: options.albumName,
			albums_too: (options.includeAlbums)?"yes":"no",
			random: (options.random)?"yes":"no",
			limit: options.limit,
			extrafields: (options.extrafields)?"yes":"no"
		}, callback);
	},

	imageProperties: function(options, callback) {
		this._request({
			cmd: "image-properties",
			protocol_version: "2.4",
			id: options.id
		}, callback);
	},

	incrementViewCount: function(options, callback) {
		this._request({
			cmd: "increment-view-count",
			protocol_version: "2.4",
			id: options.id
		}, callback);
	},

	addItem: function(options, callback) {
		/* UNIMPLEMENTED */
		this.noOp(options, callback);
	},

	noOp: function(options, callback) {
		this._request({
			cmd: "no-op"
		}, callback);
	},


	/* INTERNAL FUNCTIONS */
	_request: function(pParams, callback) {
		var cmd = pParams.cmd;
		var reqParams = this._prepareParams(pParams);
		new Ajax.Request(this.gallery_url, {
			parameters: reqParams,
			onSuccess: (function(xhr) {
				var r = this._parseResponse(xhr.responseText);
				r._params = reqParams;
				if (r.status=="0" && r.auth_token) {
					this.defaultParams['g2_authToken'] = r.auth_token;
				}

				if (callback) {
					callback.bind(this)(r);
				}
			}).bind(this)
		});
	},

	_parseResponse: function(response) {
		var lines = $A(response.split("\n"));
		var json = {};
		for (var i=1; i<lines.length; i++) {
			var line = lines[i];
			var eq = line.indexOf("=");
			var key = line.substring(0, eq);
			json._raw=lines;

			if (key.indexOf(".")>1) {
				var keyParts = key.split(".");
				var lastPart = keyParts.length-1;
				if ( !isNaN(keyParts[lastPart]) ) {
					var key1 = keyParts[1];
					keyParts[1]=keyParts[lastPart];
					keyParts[lastPart]=key1;
				}
				var sub = "";
				for (var j=0; j < keyParts.length; j++) {
					sub += isNaN(keyParts[j])?'["'+ keyParts[j] + '"]':'['+ keyParts[j] + ']';
					var x = eval('json'+sub);
					if ( !x ) {
						var nullObj = isNaN(keyParts[j+1])?'{}':'[]';
						var value = (j!=lastPart)? nullObj :'"'+line.substring(eq+1, line.length)+'"';
						eval('json'+sub + "=" + value);
					}
				}
			} else {
				json[key] = line.substring(eq+1, line.length);
			}
		}
		return json;
	},

	_parseKey: function(keyParts, value) {
		var sub = {};
		for (var i=1; i < keyParts.length; i++) {

		}
		return sub;
	},

	_prepareParams: function(pParams) {
		var reqParams = {};
		var defaults = this.defaultParams||{};
		for (var p in defaults) {
			reqParams[p] = defaults[p];
		}
		for (var p in pParams||{}) {
			var key = 'g2_form['+p+']';
			var val = pParams[p];
			reqParams[key] = val;
		}
		return reqParams;
	}

});

